//
//  HttServer.swift
//  ReportScan
//
//  Created by woniu on 2025/8/20.
//

import Foundation

class UserItem {
    var rhrId = ""
    var rhrName = ""
    var rhrIdCard = ""
    var content = ""
    var totalGroupMap:[String:String] = [:]
    
    func getGroupMap()->[String:String]{
        if !totalGroupMap.isEmpty{
            return totalGroupMap
        }
        let contentList = content.getArrayFromJSONString()
        for contentItem in contentList{
            if let contentItemDic = contentItem as? [String:Any]{
                
                let groupName = contentItemDic.strValue("groupName")
                var mesList:[String] = []
                
                let fieldResults = contentItemDic.array("fieldResults")
                for fieldItemDic in fieldResults{
                    //未完善
                    let improveList = fieldItemDic.array("improve")
                    
                    for improveItem in improveList{
                        mesList.append(improveItem.strValue("msg"))
                    }
                    
                    //错误
                    let errors = fieldItemDic.array("error")
                    for errorItem in errors{
                        mesList.append(errorItem.strValue("msg"))
                    }
                    //注意
                    let waringList = fieldItemDic.array("waring")
                    for waringItem in waringList{
                        mesList.append(waringItem.strValue("msg"))
                    }
                }
                let string = mesList.map{$0}.joined(separator: ",")
                totalGroupMap[groupName] = string
            }
        }
        return totalGroupMap
        
    }
    
}


class HttServer: NSObject {
    
    
    // 发送请求
    static func httpGetUserList(pageIndex:Int,completion: @escaping (_ re:Bool,_ dataList:[UserItem]) -> Void) {
        // 请求URL
        let urlString = "https://wnjk.2woniu.cn/wnjkapp/quality/manage/record/list"
        // 创建URL
        guard let url = URL(string: urlString) else {
            return
        }
        // 创建请求体
        let requestBody: [String: Any] = [
            "size": 300,
            "insId": 11033,
            "module": "TaskArchivesDetail",
            "page": pageIndex
        ]
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: requestBody) else {
            return
        }
        
        // 创建URLRequest
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        
        // 设置请求头
        request.setValue("br;q=1.0, gzip;q=0.9, deflate;q=0.8", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-Hans-CN;q=1.0", forHTTPHeaderField: "Accept-Language")
        request.setValue("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbnNJZCI6MTEwMzMsImFyZWFDb2RlIjoiNTExMTAyMTA4Iiwicm9sZSI6MiwiY29kZSI6ImUzNzdlYmI2MGZlYjk4YjAxMTkxN2MwMWI3ODQwNjZlMWUwODViNzFjNzcxYjAwN2IzMDE5YmZhMGFmMmY1NzAiLCJuYmYiOjE3NTU2Njg5NzksImlzSW5pdGlhbFB3ZCI6MCwibW9kdWxlIjoyNzAsImhvc3QiOiIxMjAuNzguMTc3LjEwOCIsInN0YXJ0IjoxNzU1NjcyNTc5ODM1LCJjbGllbnQiOjIsImlkIjoiMTA3NTczIn0.1UYFvfQwNIMm2HMDunUp5CQlDu0N2OHtX9zfgQqpLvo", forHTTPHeaderField: "token")
        request.setValue("Health-Doctor/2.8.8 (cn.2woniu.health.doctor; build:1; iOS 16.3.1) Alamofire/5.10.1", forHTTPHeaderField: "User-Agent")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("os=2;ver=2.8.8;ctype=2;imei=DB43B8A0-3DDB-4FED-97F4-AB53AD7B0D75", forHTTPHeaderField: "PP-User-Agent")
        
        // 计算Content-Length（可选，系统会自动添加）
        request.setValue("\(jsonData.count)", forHTTPHeaderField: "Content-Length")
        
        // 发送请求
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("请求失败，第\(pageIndex)页: \(error.localizedDescription)")
                completion(false,[])
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                print("请求失败，第\(pageIndex)页")
                completion(false,[])
                return
            }
            
            if let data = data {
                // 处理返回的数据（可以转换为JSON或模型）
                let responseString = String(data: data, encoding: .utf8)
                
                // 如果需要解析JSON，可以使用JSONSerialization
                if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    let code = json["status"] as? Int ?? -1
                    if code == 0{
                        let dataList = json["data"] as? [[String:Any]] ?? []
                        //                        print("第\(pageIndex)页，获取成功\(dataList.count)条数据")
                        var items:[UserItem] = []
                        for item in dataList{
                            let content = item["content"] as? String ?? ""
                            let model = UserItem()
                            model.rhrId = item["rhrId"] as? String ?? ""
                            model.rhrIdCard = item["rhrIdCard"] as? String ?? ""
                            model.rhrName = item["rhrName"] as? String ?? ""
                            model.content = content
                            items.append(model)
                        }
                        
                        completion(true,items)
                    }else{
                        completion(false,[])
                        print("第\(pageIndex)页，报错了\(responseString ?? "")")
                    }
                    
                }else{
                    completion(true,[])
                }
            }else{
                print("请求失败，第\(pageIndex)页")
                completion(false,[])
            }
        }
        task.resume()
    }
}


extension HttServer {
    
    
    /// 获取导入的体检档案列表数据
    /// - Parameters:
    ///   - keyword: 搜索关键词
    ///   - syncStatus: 同步状态
    ///   - matchStatus: 匹配状态
    ///   - pageNo: 页码
    ///   - pageSize: 每页大小
    ///   - completion: 完成回调
    
    // 发送请求
    static func httpGetPhyUserList(keyword: String = "",
                                   syncStatus: String = "",
                                   matchStatus: Int = 1,
                                   pageIndex: Int,completion: @escaping (_ re:Bool,_ dataList:[PhyUserItem],_ total:Int) -> Void) {
        // 构建URL
        let baseURL = "http://bmg.2woniu.cn/bmanage/third/pe/list?syncStatus=\(syncStatus)&matchStatus=1&pageNo=\(pageIndex)&pageSize=20"
        // 创建请求
        var request = URLRequest(url: URL(string: baseURL)!)
        request.httpMethod = "GET"
        
        // 设置请求头
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        request.setValue("10576", forHTTPHeaderField: "insId")
        request.setValue("http://wnkh.2woniu.cn", forHTTPHeaderField: "Origin")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("http://wnkh.2woniu.cn/", forHTTPHeaderField: "Referer")
        request.setValue("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbnNJZCI6MTA1NzYsImFyZWFDb2RlIjoiNTExMzIyMDAyIiwicm9sZSI6MiwiY29kZSI6IjVmYThlZTgxZmQ3OWQ3NTNlMjVmMTRjNTM3MDVmMjZjNjdmODViMDg4N2EzMjk2ZTJkZDY3MTc3OTEyZThkOTAiLCJuYmYiOjE3NjMzNTg2OTIsImlzSW5pdGlhbFB3ZCI6MCwibW9kdWxlIjoyNzAsImhvc3QiOiIxMjAuNzguMTc3LjEwOCIsInN0YXJ0IjoxNzYzMzYyMjkyMjM1LCJjbGllbnQiOjUsImlkIjoiMjU3MTcifQ.M0UZ-W2T1lC2YkDIQKFRx5_Mie8vHKAZg0DS-bmN4sg", forHTTPHeaderField: "token")
        request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
        
        // 发送请求
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("请求失败，第\(pageIndex)页: \(error.localizedDescription)")
                completion(false,[],0)
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                print("请求失败，第\(pageIndex)页")
                completion(false,[],0)
                return
            }
            
            if let data = data {
                // 处理返回的数据（可以转换为JSON或模型）
                let responseString = String(data: data, encoding: .utf8)
                // 如果需要解析JSON，可以使用JSONSerialization
                if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    let code = json["status"] as? Int ?? -1
                    if code == 0{
                        let dataMap = json.dictionary("data")
                        let dataList = dataMap["results"] as? [[String:Any]] ?? []
                        let total = dataMap.intValue("total")
                        print("第\(pageIndex)页，获取成功\(dataList.count)条数据")
                        var items:[PhyUserItem] = []
                        for item in dataList{
                            
                            let model = PhyUserItem()
                            model.no = item.strValue("peEn")
                            model.date = item.strValue("peTime")
                            model.name = item.strValue("name")
                            let birthDay = item.strValue("birthDay")
                            let age = DateUtil.caculateAge(birthday: birthDay)
                            model.age = age <= 0 ? "无" : "\(age)"
                            
                            model.gender = item.intValue("gender") == 2 ? "女" : "男"
                            model.phone = item.strValue("phoneNumber")
                            model.idCard = item.strValue("idCard")
                            model.archives = item.strValue("rhrId").isEmpty ? "未建档" : "已建档"
                            
                            let syncStatus = item.intValue("syncStatus")
                            if syncStatus == 1{
                                model.uploadState = "已上传"
                            }else{
                                model.uploadState = "上传失败:\(item.strValue("syncErrorMsg"))"
                            }
                            
                            model.insName = item.strValue("insName")
                            model.address = item.strValue("address")
                            let peType = item.intValue("peType")
                            model.peType = peType == 0 ? "个检" : "其他"
                            model.reDate = item.strValue("updateTime")
                            
                            items.append(model)
                        }
                        
                        completion(true,items,total)
                    }else{
                        completion(false,[],0)
                        print("第\(pageIndex)页，报错了\(responseString ?? "")")
                    }
                    
                }else{
                    completion(true,[],0)
                }
            }else{
                print("请求失败，第\(pageIndex)页")
                completion(false,[],0)
            }
        }
        task.resume()
    }
}
